package com.qf.springbootproject.config;


import com.qf.springbootproject.shiro.CustomRealm;
import com.qf.springbootproject.shiro.JwtShiroFilter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager,ShiroFilterChainDefinition shiroFilterChainDefinition) {

        final ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置 starter依赖自动添加的  securityManager 对象
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 设置要使用的所有shiro的过滤器
        final HashMap<String, Filter> filtermap = new HashMap<>();
        filtermap.put("jwt", new JwtShiroFilter());  // 自定义过滤器添加
        filtermap.put("anon", new AnonymousFilter()); // 添加shiro原有的匿名过滤器
        shiroFilterFactoryBean.setFilters(filtermap);

        // 设置url和过滤器的匹配关系
        final Map<String, String> filterChainMap = shiroFilterChainDefinition.getFilterChainMap();
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);

        return shiroFilterFactoryBean;
    }


    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {

        final DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();

        // 放行指定的 url
        definition.addPathDefinition("/user/get/**", "anon");
        definition.addPathDefinition("/index/indeximg", "jwt");


        return definition;

    }

    @Bean
    public Realm realm() {
        final CustomRealm customRealm = new CustomRealm();

        // 设置密码匹配器
        final HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();

        hashedCredentialsMatcher.setHashIterations(Constants.HASH_TIMES);
        hashedCredentialsMatcher.setHashAlgorithmName("md5");

        customRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        return customRealm;
    }
}
